package org.needcoke.hs.signature;

import lombok.extern.slf4j.Slf4j;
import org.needcoke.hs.util.SignatureUtil;
import java.nio.charset.StandardCharsets;

/**
 * 签名算法
 */
@FunctionalInterface
public interface SignFunction {

    /**
     * 签名函数
     *
     * @param plaintext 明文
     * @param key       秘钥(非必传)
     * @return 签名
     */
    String sign(String plaintext, String key);

    class DefaultSignFunction implements SignFunction {
        @Override
        public String sign(String plaintext, String key) {
            return SignatureUtil.md5(plaintext, StandardCharsets.UTF_8);
        }
    }

    class Sha256SignFunction implements SignFunction {

        @Override
        public String sign(String plaintext, String key) {
            return SignatureUtil.sha256(plaintext, StandardCharsets.UTF_8);
        }
    }

    @Slf4j
    class RSA2SignFunction implements SignFunction {

        @Override
        public String sign(String plaintext, String key) {
            try {
                return SignatureUtil.sha256WithRSA(plaintext, key);
            } catch (Exception e) {
                log.error("签名失败! plaintext = {} , key = {}", plaintext, key);
                throw new RuntimeException("签名失败! plaintext = " + plaintext + " , key = " + key, e);
            }
        }
    }

    @Slf4j
    class RSASignFunction implements SignFunction {

        @Override
        public String sign(String plaintext, String key) {
            try {
                return SignatureUtil.sha1WithRSA(plaintext, key);
            } catch (Exception e) {
                log.error("签名失败! plaintext = {} , key = {}", plaintext, key);
                throw new RuntimeException("签名失败! plaintext = " + plaintext + " , key = " + key, e);
            }
        }
    }

    SignFunction defaultSignFunction = new DefaultSignFunction();

    SignFunction sha256SignFunction = new Sha256SignFunction();

    SignFunction rsa2SignFunction = new RSA2SignFunction();

    SignFunction rsaSignFunction = new RSASignFunction();

}
